package com.xxh.market.dao.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.xxh.market.dao.OrderDao;
import com.xxh.market.entity.Order;
import com.xxh.market.utils.DataUtil;

import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl  implements OrderDao {
    //生成一条订单记录，并返回自增主键
    @Override
    public int insertOrder(Order order) {
        try {
            Long key = Db.use().insertForGeneratedKey(
                    Entity.create("orders")
                            .set("orderno", order.getOrderno())
                            .set("uid", order.getUid())
                            .set("price",order.getPrice())
                            .set("ordertime",order.getOrdertime())
            );
            int anInt = NumberUtil.parseInt(key.toString());
            return anInt;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Order> selectOrdersByUser(int uid) {
        try {
            List<Order> orders = new ArrayList<>();
            List<Entity> entityList = Db.use().query("select * from orders where uid =?", uid);
            entityList.stream().forEach( entity -> {
                Order order = new Order();
                order.setOrderno(entity.getStr("orderno"));
                order.setUid(entity.getInt("uid"));
                String ordertime = entity.getStr("ordertime");
                DateTime dateTime = DateUtil.parse(ordertime, "yyyy-MM-dd HH:mm:ss");
                order.setOrdertime(dateTime);
                order.setPrice(entity.getDouble("price"));
                orders.add(order);
            });
            return orders;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
